import 'package:flutter/material.dart';
import 'package:jd_flutter/base/widget/ui/hint_dialog.dart';
import 'package:permission_handler/permission_handler.dart';

extension PermissionUtil on Permission {
  requestPermission(
    BuildContext context,
    Function success, {
    String? title,
  }) async {
    if (await isGranted) {
      success.call();
    } else if (await request() == PermissionStatus.granted) {
      success.call();
    } else {
      bool isPermanentlyDenied = await this.isPermanentlyDenied;
      showHint(title, isPermanentlyDenied, success, context);
    }
  }

  showHint(String? title, bool isPermanentlyDenied, Function success,
      BuildContext context) {
    HintDialog(
      content: title ?? '当前操作需要您同意权限',
      leftText: "手动开启",
      leftButtonFunction: (context) {
        Navigator.pop(context);
        openAppSettings();
      },
      rightText: '再试一次',
      rightButtonFunction: () {
        if (isPermanentlyDenied) return null;
        return (context) {
          Navigator.pop(context);
          requestPermission.call(context, success, title: title);
        };
      }(),
    ).show(context);
  }
}
